package com.bojiu.lawsearch.lawsearch.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.net.URLEncoder;
import java.security.SecureRandom;

@Slf4j
public class EncryptUtil {

	/**
	 * 加密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data) throws Exception {
		byte[] bt = encrypt(data.getBytes(), UtilConstants.KEY.getBytes());
		String strs = Base64.encodeBase64String(bt);
		return strs;
	}
	
	public static String encryptUrlEncode(String data) throws Exception {
		byte[] bt = encrypt(data.getBytes(), UtilConstants.KEY.getBytes());
		String strs = Base64.encodeBase64String(bt);
		log.debug("strs is :{}",strs);
		return URLEncoder.encode(strs, "UTF-8");
	}


	/**
	 * 解密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String data) throws Exception {
		byte[] bt = Base64.decodeBase64(data);
		byte[] result = decrypt(bt, UtilConstants.KEY.getBytes());
		return new String(result);
	}

	private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		// 生成可信任的随机数源
		SecureRandom secureRandom = new SecureRandom();
		DESKeySpec desKeySpec = new DESKeySpec(key);

		// 创建秘钥工厂 最后转成key对象
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(UtilConstants.DES);
		SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

		// Cipher 初始化最终完成加密操作
		Cipher cipher = Cipher.getInstance(UtilConstants.DES);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);
		return cipher.doFinal(data);
	}

	private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
		// 生成可信任的随机数源
		SecureRandom secureRandom = new SecureRandom();
		DESKeySpec desKeySpec = new DESKeySpec(key);

		// 创建秘钥工厂 最后转成key对象
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(UtilConstants.DES);
		SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

		// Cipher 初始化最终完成解密操作
		Cipher cipher = Cipher.getInstance(UtilConstants.DES);
		cipher.init(Cipher.DECRYPT_MODE, secretKey, secureRandom);
		return cipher.doFinal(data);
	}

	public static void main(String[] args) throws Exception {
		String ss = "hHXcKqkINPJXk%252BavNE23Y8M3VQGUfCkK8sX12odD4t0Huo3V77Esdcws4RzJeXmQ";
		String aaa = decrypt(ss);
		System.out.println(aaa);
	}
}
